package online.hashmall.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import online.hashmall.dao.SysUserDao;
import online.hashmall.dto.LoginDTO;
import online.hashmall.entity.SysUser;
import online.hashmall.enums.DeviceType;
import online.hashmall.except.SysException;
import online.hashmall.service.LoginService;
import online.hashmall.util.SecurityUtil;
import online.hashmall.vo.LoginVO;
import org.springframework.stereotype.Service;

/**
 * @author jpq
 * @email jinpqa@163.com
 * @since 2024/5/18 上午10:09
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private SysUserDao userDao;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        SysUser sysUser = loadUserByUsername(loginDTO.getUsername(), loginDTO.getPassword());
        // 生成token
        SecurityUtil.loginByDevice(sysUser, DeviceType.PC);
        LoginVO loginVO = new LoginVO();
        loginVO.setAccessToken(StpUtil.getTokenValue());
        return loginVO;
    }

    @Override
    public void logout() {
        // 日志

        StpUtil.logout();
    }

    /**
     * 通过账号名称登录
     *
     * @param username 账号名称
     * @param password 账号密码
     * @return
     */
    private SysUser loadUserByUsername(String username, String password) {
        SysUser sysUser = userDao.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, username));

        if (sysUser == null) {
            throw new SysException("登录用户：" + username + " 不存在.");
        }
        return sysUser;
    }
}
